package com.example.springboot.demo.controller;

import com.example.springboot.demo.model.MassageInfo;
import com.example.springboot.demo.service.MassageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RequestMapping("/message")
@RestController
public class MassageController {
    @Autowired
    private MassageService massageService;

//    List<MassageInfo> massageInfos=new ArrayList<>();

    //produces = "application/json" 表示返回的响应体内容类型为 JSON
    @RequestMapping(value = "/publish",produces = "application/json")
    //@RequestBody 表示将请求体中的JSON内容转换为 MassageInfo 对象
    public String publish(@RequestBody MassageInfo massageInfo){
        if(!StringUtils.hasLength(massageInfo.getFrom())
        ||!StringUtils.hasLength(massageInfo.getTo())
        ||!StringUtils.hasLength(massageInfo.getMessage())){
            return "{\"ok\":0}";
        }
        // 调用服务层方法插入消息
        massageService.insert(massageInfo);
//        massageInfos.add(massageInfo);
        return "{\"ok\":1}";
    }

    @RequestMapping("/list")
    public List<MassageInfo> getList(){
        return  massageService.selectAll();
    }
}
